<?php

class Application_Model_Usuario extends Zend_Db_Table
{
    const ROLE_ALL   = 'all';
    const ROLE_ADMIN = 'admin';

    protected $_name    = 'tb_usuario';
    protected $_primary = array('id_usuario');

    /**
     * Faz o login caso o login e senha estejam corretos
     * @param string $login
     * @param string $senha
     * @return boolean
     */
    public function login($login, $senha)
    {
        $this->logout();

        $db          = Zend_Db_Table::getDefaultAdapter();
        $authAdapter = new Zend_Auth_Adapter_DbTable($db, 'tb_usuario', 'ds_login', 'ds_senha', 'md5(?)');

        $authAdapter->setIdentity($login)
                    ->setCredential($senha);
        $result = $authAdapter->authenticate();
        if ($result->isValid()) {
            $identity = $authAdapter->getResultRowObject(null, 'ds_senha');

            // @TODO: Verificar status do usuário (ativo ou inativo)

            // Administrador
            if ($identity->id_perfil_usuario == 1) {
                $identity->role = Application_Model_Usuario::ROLE_ADMIN;
            }

            $auth = Zend_Auth::getInstance();
            $auth->getStorage()->write($identity);

            $usuario                   = $this->find($identity->id_usuario)->current();
            $usuario->dt_ultimo_acesso = date('Y-m-d H:i:s');
            $usuario->save();

            return true;
        }
        return false;
    }

    /**
     * Faz o logout do usuario
     * @return boolean
     */
    public function logout()
    {
        $auth = Zend_Auth::getInstance();
        $auth->clearIdentity();
    }

}